package com.baizhi.aspect;


import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.AdminLogDAO;
import com.baizhi.entity.Admin;
import com.baizhi.entity.AdminLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Configuration
public class LogAop {

    @Autowired
    private AdminLogDAO adminLogDAO;


    /**
     * 确定切入点
     */
    @Pointcut("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void adminLog(){}


    /**
     * 确定增强
     */

    @After("adminLog()")
    public void logPoint(JoinPoint joinPoint){
        /**
         * 获取日志数据
         */
        AdminLog adminLog = new AdminLog();

//        获取时间
        adminLog.setLogDate(new Date());

//        从session中获取id
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        System.out.println("admin = " + admin);
//        adminLog.setAdminId(admin.getId());
        adminLog.setAdminId(101);

//        获取IP
        adminLog.setLogIp(IPKit.getIpAddrByRequest(request));

//        获取自定义自定义注解值
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);

        adminLog.setLogContent(logAnnotation.content());
        adminLog.setLogType(logAnnotation.type());


//        添加至数据库
        adminLogDAO.insertAdminLog(adminLog);

    }
}
